<template>
  <MkDialogEdit ref='dialogRef' v-model:isEdit='ctx.isEdit' @submit='submit'>
    <MkForm :model='ctx.entity' ref='formRef' formId='BasXueYeChanPin'>
      <MkInput label='产品代码' v-model='ctx.entity.id' prop='id' :isEdit='ctx.isAdd' required />
      <MkInput label='产品名称' v-model='ctx.entity.mingCheng' prop='mingCheng' :isEdit='ctx.isEdit' required />
      <MkSelectBasEntity label='血液品种' v-model='ctx.entity.pinZhongId' prop='pinZhongId' :isEdit='ctx.isEdit'
        entity="BasXueYePinZhong" @change="change" required />
      <MkSelectBasEntity label='收费设置' v-model='ctx.entity.xueYeChanPinFeiYongId' prop='xueYeChanPinFeiYongId'
        :isEdit='ctx.isEdit' entity="BasXueYeChanPinFeiYong" required />
      <MkSelectEnum label="血液大类" v-model="ctx.entity.daLei" prop='daLei' :isEdit="false" />
      <MkInput label='产品别名，汇总用' v-model='ctx.entity.bieMing' prop='bieMing' :isEdit='ctx.isEdit' v-if="!ctx.isAdd" />
      <MkInput label='备注' v-model='ctx.entity.remark' prop='remark' :isEdit='ctx.isEdit' />
      <MkIsEnabled v-model='ctx.entity.isEnabled' :isEdit='ctx.isEdit' />
    </MkForm>
  </MkDialogEdit>
</template>

<script lang='ts' setup>
import { BasXueYeChanPinApi, BasXueYeChanPinOutput } from '/@/api/bas/BasXueYeChanPin';
import { xueYePinZhongList, refreshBasXueYeChanPin } from '/@/stores/baseInfo';
import { isNull, clog, showSuccess } from '/@/utils';

const emits = defineEmits(['query'])
const ctx = reactive({
  isEdit: false,
  isAdd: false,
  entity: {} as BasXueYeChanPinOutput,
});

const dialogRef = ref();
const formRef = ref();

/** 打开弹框 */
const open = async (row: BasXueYeChanPinOutput) => {
  dialogRef.value.show();
  if (isNull(row?.id)) {
    ctx.isEdit = true;
    ctx.isAdd = true;
    ctx.entity = { isEnabled: true } as BasXueYeChanPinOutput;
  } else {
    ctx.isAdd = false;
    ctx.isEdit = false;
    ctx.entity = JSON.parse(JSON.stringify(row));
  }
};

const close = () => {
  dialogRef.value?.close();
  emits('query')
};

const change = async (val: string) => {
  var item = xueYePinZhongList.value.find(item => item.id == ctx.entity.pinZhongId);
  ctx.entity.daLei = item?.daLei ?? "";
}

const submit = async () => {
  if (!ctx.isEdit) {
    close();
    return;
  }
  // 表单验证
  const validate = await formRef?.value?.validate();
  if (!validate) return;
  if (ctx.isAdd) {
    await BasXueYeChanPinApi.add(ctx.entity);
  } else {
    await BasXueYeChanPinApi.update(ctx.entity);
  }
  // 刷新前端缓存
  refreshBasXueYeChanPin();
  showSuccess();
  close();
};

defineExpose({ open })
</script>